//1.本地存储API封装

//存储数据
export const setStorage = (key, value) => {
	try {
		wx.setStorageSync(key, value)
	} catch (error) {
		console.error(`存储指定 ${key} 数据发生了异常`, error)
	}
}

//从本地读取指定key的数据
export const getStorage = (key) => {
	try {
		const value = wx.getStorageSync(key)
		if (value) {
			return value
		}
	} catch (error) {
		console.error(`读取指定 ${key} 数据发生了异常`, error)
	}
}

//从本地移除指定key的数据
export const removeStorage = (key) => {
	try {
		wx.removeStorageSync(key)
	} catch (error) {
		console.error(`移除指定 ${key} 数据发生了异常`, error)
	}
}

//从本地清空缓存的数据
export const clearStorage = () => {
	try {
		wx.clearStorageSync()
	} catch (error) {
		console.error(`清空数据发生了异常`, error)
	}
}

//2.封装异步存储API

//异步将数据存储到本地
export const asyncSetStorage = (key, data) => {
	return new Promise((resolve) => {
		wx.setStorage({
			key,
			data,
			complete(res) {
				resolve(res)
			}
		})
	})
}

//异步从本地读取指定key的数据
export const asyncGetStorage = (key) => {
	return new Promise((resolve) => {
		wx.getStorage({
			key,
			complete(res) {
				resolve(res)
			}
		})
	})
}

//异步从本地移除指定key的数据
export const asyncRemoveStorage = (key) => {
	return new Promise((resolve) => {
		wx.removeStorage({
			key,
			complete(res) {
				resolve(res)
			}
		})
	})
}

//异步从本地清空缓存的数据
export const asyncClearStorage = () => {
	return new Promise((resolve) => {
		wx.clearStorage({
			complete(res) {
				resolve(res)
			}
		})
	})
}
